package com.crm.handler;


import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.crm.exception.CustomException;
import com.crm.exception.ReturnViewException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理
 */
public class IntegrateExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        boolean isAjaxRequest = "XMLHttpRequest".equals(request.getHeader("x-requested-with"));

        if (isAjaxRequest) {
            CustomException customException = (ex instanceof CustomException)
                    ? (CustomException) ex
                    : new CustomException("系统未知错误");

            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("message", customException.getMessage());

            FastJsonJsonView view = new FastJsonJsonView();
            view.setAttributesMap(map);

            return new ModelAndView(view);
        } else {
            ReturnViewException returnViewException = (ex instanceof ReturnViewException)
                    ? (ReturnViewException) ex
                    : new ReturnViewException("page/error/index", ex.getMessage());

            ModelAndView modelAndView = new ModelAndView("redirect:/" + returnViewException.getViewName());
            modelAndView.addObject("errorMessage", returnViewException.getMessage());

            return modelAndView;
        }
    }
}
